#!/usr/bin/python3
from openpyxl import load_workbook
import os, gc
from .Base_Plugin import Base_Plugin


class Sheet_Create_Sheets_By_Directory(Base_Plugin):
    """按目录创建工作表插件"""

    def __init__(self, context) -> None:
        super().__init__()
        self.context = context

    def run(self, workspace, source):
        workbook = load_workbook(os.path.join(workspace, source))
        _directory = workbook["目录"]
        _style_config = workbook["工程配置"]
        new_table_style_fill = _style_config["C3"].fill.copy()  # 新增表的样式
        normal_style_fill = _style_config["C2"].fill.copy()  # 未作任何变更的样式
        for row in _directory.rows:
            if row[1].row < 2:
                continue

            table_name = row[1].value
            if table_name is None:
                break
            table_name = table_name.strip()
            table_description = row[2].value.strip()

            if table_description not in workbook.sheetnames:
                new_sheet = workbook.copy_worksheet(workbook["表模板"])
                new_sheet.title = table_description
                new_sheet["A1"] = table_description
                new_sheet["A2"] = table_name
                row[1].fill = new_table_style_fill
                self.processed += 1
            else:
                row[1].fill = normal_style_fill
        return_val = None
        saved_name = r"SheetsCreated.xlsx"
        new_path = os.path.join(workspace, saved_name)
        if os.path.exists(new_path):
            os.remove(new_path)
        workbook.save(new_path)
        return_val = saved_name
        del workbook
        gc.collect()
        return return_val
